<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
      label-position="left">
      <div class="title-container">
        <h3 class="title">生生智慧渔业-社会化服务</h3>
      </div>

      <el-form-item prop="account">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="account" v-model="loginForm.username" placeholder="请输入用户名" name="username" type="text" tabindex="1"
          auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入密码"
          name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin">登 录</el-button>

      <div class="tips">
        <el-checkbox v-model="isRemenber"><span style="color: #ffffff;">记住密码</span></el-checkbox>
        <!-- <span style="margin-right:20px;">username: admin</span>
        <span> password: 123456</span> -->
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie';
import CryptoJS from 'crypto-js';
import axios from "axios";

export default {
  name: 'Login',
  data () {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不得少于6位数'))
      } else {
        callback()
      }
    }
    return {
      isRemenber: true, //是否记住密码
      loginForm: {
        // username: 'admin',
        // password: '123456'
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        let moduleIndex = route.query.moduleIndex ? route.query.moduleIndex : 4
        this.redirect = route.query && route.query.redirect
        this.$store.dispatch('app/chooseMdule', moduleIndex)
      },
      immediate: true
    }
  },
  created () {
    this.loginVerification()
  },
  mounted () {
    this.getUserPassword()
  },
  methods: {
    loginVerification () {
      let username = this.$route.query.account
      let password = this.$route.query.password
      let accessToken = this.$route.query.accessToken
      if (accessToken) {
        axios.post(
          'http://fishery.ssagroup.cn:9091/system/user/authenticationByAccessToken',
          { "accessToken": accessToken.replaceAll(' ', '+'), "applicationName": "smart" },
          { headers: { token: Cookies.get("token") } }
        ).then((res) => {
          if (res.data && res.data.code == 200) {
            setToken(res.data.data)
            this.getInfo()
          } else {
            let msgInfo = ''
            switch (res.data.message) {
              case "错误的凭证. error: 1":
                msgInfo = '系统名错误'
                break;
              case "错误的凭证. error: 2":
                msgInfo = '使用了错误的key进行解密'
                break;
              case "错误的凭证. error: 3":
                msgInfo = '凭证格式错误'
                break;
              case "错误的凭证. error: 4":
                msgInfo = '拼接的系统名和传入参数的系统名不一致'
                break;
              case "错误的凭证. error: 5":
                msgInfo = '凭证过期'
                break;
              case "错误的凭证. error: 6":
                msgInfo = '对应电话号码未绑定用户'
                break;
              default:
                msgInfo = '未配置手机号请联系管理员给您配置手机号吧！'
            }
            this.$message.error(msgInfo)
          }
        }).catch((err) => {
          console.log(err);
        });
        return
      }
      if (username && password) {
        this.goLogin({ username: username, password: password })
      }
    },
    remenberUser () {
      // 登录成功后 判断是否选择了勾选密码
      if (this.isRemenber) {
        //添加cookie
        Cookies.set('userName', this.loginForm.username, {
          expires: 30
        })
        //使用crypto-js进行加密（需要npm加载后引入） 并存储到cookie中 此处CAC174-159-SSSLSD 为秘钥 
        Cookies.set('userPwd', CryptoJS.AES.encrypt(this.loginForm.password, 'CAC174-159-SSSLSD'), {
          expires: 30 // 存储30天
        })
      } else {
        // 删除cookie
        Cookies.remove('userName')
        Cookies.remove('userPwd')
      }
    },
    getUserPassword () {
      const userName = Cookies.get('userName') ? Cookies.get('userName') : '';
      const enPassword = Cookies.get('userPwd') ? Cookies.get('userPwd') : '';
      if (enPassword) {
        // 对密码进行解密
        this.loginForm.password = CryptoJS.AES.decrypt(enPassword, 'CAC174-159-SSSLSD').toString(CryptoJS.enc.Utf8);
        // 将是否记住密码置为true
        this.isRemenber = true;
      } else {
        this.loginForm.password = '';
      }
      this.loginForm.username = userName;
    },
    showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.goLogin(this.loginForm)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async getInfo () {
      const res = await this.$store.dispatch('user/getInfo')
      console.log('用户信息', res)
      if (res.code == 200) {
        if (!res.status) {
          let roles = res.data.roles
          let routerList = []
          let routes = this.$router.options.routes
          roles.forEach(role => {
            routerList = routerList.concat(JSON.parse(role.menu))
          })
          console.log(routerList)
          // routerList = ["/agricultural-supplies", "/agricultural-resources-management", "/agricultural-info-management", "/agricultural-sort-management", "/distribution-management", "/pickup-location-management", "/order-management", "/artificial-order-management", "/order-handling-designated-spot", "/order-handling", "/customer-management", "/customer-service-management", "/customer-service-chat", "/chatting-records", "/breed-aquatics-popular", "/knowledge-base-management", "/knowledge-classification-management", "/article-management", "/article-examine", "/video-type-management", "/video-group-management", "/video-management-ungroup", "/video-management", "/video-examine", "/product-library", "/product-sort-management", "/product-info-management"]
          sessionStorage.setItem('userName', res.data.userName)
          sessionStorage.setItem('auto_router', JSON.stringify(routerList))
          sessionStorage.setItem('avatar', res.data.avatar)
          sessionStorage.setItem('userId', res.data.userId)
          sessionStorage.setItem('userType', res.data.userType)
          this.remenberUser()  //记住密码
          if (res.data.status == "0") {  //'0'启用 '1'停用 
            sessionStorage.setItem('status', res.data.status)
            if (routerList.length) {
              let pRouterList = routes.filter(item => {
                return JSON.stringify(routerList).indexOf(item.path) !== -1 && item.hasOwnProperty('children') && item.children.length > 0
              })
              this.$router.push({ path: pRouterList[0].children[0].path })
            } else {
              this.$message('该账户未配置菜单！')
            }
          } else {
            this.$message('该账户未启用！')
          }
        } else {
          this.$message('该账户已经停用！')
        }
      } else {
        this.$message('未获取到用户信息！')
      }
      this.loading = false
    },
    goLogin (loginForm) {
      this.$store.dispatch('user/login', loginForm).then(async () => {
        this.getInfo()
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background: url(../../assets/backgroundImg/app-download.jpg);

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(255, 255, 255, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  ::v-deep .el-button {
    background: #067ad9;
  }
}
</style>
